#include <sys/socket.h>

#include <errno.h>
#include <stdio.h>

#include "Listener.h"

#include "CBSocket.h"

cbsocket::Listener::Listener(int fd, cbsocket::CBSocket* sockMgr, std::tr1::function<AbstractCallback*(int)> const& callbackMaker):
AbstractCallback(fd),
sockMgr(sockMgr),
callbackMaker(callbackMaker)
{
}

void cbsocket::Listener::dataReady()
{
    while(true)
    {
        int clientfd = accept4(fd, 0, 0, SOCK_NONBLOCK);
        if(clientfd >= 0)
        {
            sockMgr->addSocket(clientfd, callbackMaker(clientfd));
        }
        else
        {
            if(errno != EAGAIN && errno != EWOULDBLOCK)
                perror("accept4");
            break;
        }
    }
}

bool cbsocket::Listener::needCleanUp()
{
    return false;
}
